package com.mjk.common.core.jdbc.ibatis.typehandler.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import javax.sql.rowset.serial.SerialClob;
import java.sql.*;

public class SerialClobTypeHandler extends BaseTypeHandler<SerialClob> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, SerialClob parameter, JdbcType jdbcType) throws SQLException {
        Clob clob = ps.getConnection().createClob();
        if (parameter.length() > 0) {
            clob.setString(1, parameter.getSubString(1, (int) parameter.length()));
        } else {
            clob.setString(1, "");
        }
        ps.setClob(i, clob);
    }

    @Override
    public SerialClob getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Clob clob = rs.getClob(columnName);
        if (clob != null) {
            return new SerialClob(clob);
        }
        return null;
    }

    @Override
    public SerialClob getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Clob clob = rs.getClob(columnIndex);
        if (clob != null) {
            return new SerialClob(clob);
        }
        return null;
    }

    @Override
    public SerialClob getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Clob clob = cs.getClob(columnIndex);
        if (clob != null) {
            return new SerialClob(clob);
        }
        return null;
    }
}
